//
//  DeviceDetailViewController.swift
//  TimeBoat
//
//  Created by Jun on 2022/9/5.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import Foundation

@objc class DeviceDetailViewController: BaseViewController {
    public var mDeviceItem: DeviceListItem?
    
    @IBOutlet var mDeviceIMEILable: UILabel!
    @IBOutlet var mDeviceTypeLable: UILabel!
    
    @objc static func viewController() -> DeviceDetailViewController {
        return DeviceDetailViewController()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "删除设备"
        updateDeviceInfo()
    }
    
    private func updateDeviceInfo() {
        self.mDeviceIMEILable.text = self.mDeviceItem?.imei
        self.mDeviceTypeLable.text = self.mDeviceItem?.name
    }
    
    @discardableResult
    private func deleteDeviceRequest(completion: APICompletion<NSObject>? = nil) -> APITASK? {
        let token = AccountManager.shareAccount().token()
        if (nil != token && nil != self.mDeviceItem?.mac && nil != self.mDeviceItem?.name) {
            var params = [String: Any]()
            params["token"] = token
            params["mac"] = self.mDeviceItem!.mac
            params["name"] = self.mDeviceItem!.name
            
            return API.POST("device/delete", params, completion)
        }
        
        return nil
    }
    
    @IBAction func btnDeleteClick() {
        let alertVC = UIAlertController.init(title: "提示", message: "是否删除此设备？", preferredStyle: .actionSheet)
        alertVC.addAction(UIAlertAction.init(title: "确定", style: .destructive, handler: { action in
            Log.debug("click confirm")
            self.deleteDeviceHandle()
        }))
        
        alertVC.addAction(UIAlertAction.init(title: "取消", style: .default, handler: { action in
            Log.debug("click cancel")
        }))
        
        self.present(alertVC, animated: true)
    }
    
    private func deleteDeviceHandle() {
        deleteDeviceRequest { [weak self] result in
            if (result.suc) {
                HUD.showSuc(msg: "删除成功", delay: 0, in: nil)
                
                AccountManager.shareAccount().clearDeviceList()
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
                    self?.navigationController?.popViewController(animated: true)
                }
            } else {
                HUD.showFail(msg: "删除失败", delay: 0, in: nil)
            }
        }
    }
}
